package com.learn.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/ribbon")
public class RibbonConsumerController {
    // 使用Ribbon负载均衡后，通过应用名（spring.application.name）访问提供方，具体使用哪个服务提供方由负载均衡策略决定
    private final String DEPT_URL = "http://PROJECT-SERVER-DEPT/dept";
    private final String NOTICE_URL = "http://PROJECT-SERVER-NOTICE/notice";
    
    @Autowired
    private RestTemplate restTemplateRibbon;
    
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    
    @PostMapping("/restTemplate/findAllDept")
    public String findAllDept() {
        return restTemplateRibbon.postForObject(DEPT_URL + "/findAllDept", null, String.class);
    }
    
    @PostMapping("/restTemplate/findAllNotice")
    public String findAllNotice() {
        return restTemplateRibbon.postForObject(NOTICE_URL + "/findAllNotice", null, String.class);
    }
    
    @GetMapping("/info/loadBalancerClient")
    public LoadBalancerClient loadBalancerClient() {
        //获取服务提供方信息
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("PROJECT-SERVER-DEPT");
        System.out.println(serviceInstance.getHost() + " : " + serviceInstance.getPort() + " : " + serviceInstance.getUri() + " : " + serviceInstance.getServiceId());
        
        return loadBalancerClient;
    }
}
